﻿<!DOCTYPE html>
<html lang="en">

	<head>
		<meta charset="UTF-8">
		<title>Ajax多个异步请求</title>
		<script src="http://libs.baidu.com/jquery/1.9.0/jquery.js"></script>
		<style>
			span.spanClickCss {
				cursor: pointer;
				color: #61C0FA;
			}
		</style>
		<script type="text/javascript">
			$(function() {
				$("#ck").click(function() {
					console.log("将源码添加到TFS，连接TFS开发，签入签出。保持版本！");
					initData();
				});

				$("#BtnDefrred").click(function() {
					deferredTest();
				});
			});

			function initData() {
				var ajax22 = $.ajax({
					url: "../jsondata/class.json",
					data: returndata(),
					success: function(data) {
						var json = data;
						alert("ajax2 page success")
					},
					statusCode: {
						404: function() {
							alert("ajax2 page not found");
						}
					}
				});

				var ajax11 = $.ajax({
					url: "../jsondata/grade.json",
					data: returndata(),
					success: function(data) {
						var json = data;
						alert("ajax1 page success")
					},
					statusCode: {
						404: function() {
							alert("ajax1 page not found");
						}
					}
				});

				$.when(ajax11, ajax22)
					.done(function() {
						alert("The Ajax is Done");
					})
					.fail(function() {
						alert("The Ajax is Fail");
					});
			}

			function returndata() {
				var jsonObj = new Object();
				jsonObj.xqdmbid = $(".xqdmbIDhtml").val();
				jsonObj.xddmbid = $(".xddmbIDhtml").val();
				jsonObj.xddmbid = $(".xddmbIDhtml").val();

				return jsonObj;
			}

			var wait = function() {
				var dtd = $.Deferred(); //【推荐】在函数内部，新建一个Deferrd对象

				var tasks = function() {
					alert("执行完毕！");

					/*
					 * resolve：已完成
					 * reject：已失败
					 */
					dtd.resolve(); //改变Deferrd对象的执行状态
				};

				setTimeout(tasks, 3000);

				return dtd;
			};

			function deferredTest() {
				$.when(wait())
					.done(function() {
						alert("哈哈，成功了！");
					})
					.fail(function() {
						alert("失败了，糟心");
					});
			}
		</script>
	</head>

	<body>
		<p>
			<h3>1、Ajax的加载顺序与when里面调用函数的顺序无关，只与js页面的顺序有关！</h3>
			<span class="spanClickCss" id="ck">Ajax顺序同步加载</span></p>
		<p>
			<h3>2、JQuery Deferred</h3>
			<span class="spanClickCss" href="javascript:void(0);" id="BtnDefrred">JQueryDeferred实例</span></p>
	</body>

</html>